package com.bw.usercenter.sq

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import com.bw.usercenter.model.protocol.resp.UserBean
import org.jetbrains.anko.db.ManagedSQLiteOpenHelper

class MySQHelper(ctx: Context) :
    ManagedSQLiteOpenHelper(ctx, DB_NAME, null, CURRENT_VERSION) {

    companion object{
        private const val TAG = "MySQHelper"
        //数据库名
        var DB_NAME= "user.db"
        //表名
        var TABLE_NAME="user_table"
        //当前版本
        var CURRENT_VERSION = 1


    }


    override fun onCreate(db: SQLiteDatabase?) {
        db?.execSQL("create table $TABLE_NAME(id Integer primary autoincrement,name varchar(20),pass varchar(20),sex varchar(20))")
        use {
            insert(UserBean())
            query()
        }

    }

     fun query():ArrayList<UserBean> {
        var userlise : ArrayList<UserBean> = arrayListOf()
        use {
            val cursor= query("$TABLE_NAME",null,null,null,null,null,null)
            if (cursor.moveToFirst()){
                while (cursor.moveToNext()){
                    val user = UserBean()
                    user.name = cursor.getString(cursor.getColumnIndex("name"))
                    user.pass = cursor.getString(cursor.getColumnIndex("pass"))
                    user.sex = cursor.getString(cursor.getColumnIndex("sex"))
                    userlise.add(user)
                }
            }
        }
        return userlise
    }
    public fun insert(user:UserBean):Long {
        var result:Long = -1
        val cv = ContentValues()
        cv.put("name",user.name)
        cv.put("pass",user.pass)
        cv.put("sex",user.sex)
        use {
            result = insert(TABLE_NAME,"",cv)
        }
        if (result==-1L){
            return result
        }
        return result
    }

/*    private fun insert(userlist: MutableList<UserBean>): Long {

        for (i in userlist.indices){
            val info = userlist[i]
            var tempArray:List<UserBean>
            if (info.name.isNotEmpty()){

            }
            use {
                result = insert(TABLE_NAME,"",)
            }
        }
        return 1
    }*/

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {

    }
}